package com.gy.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.net.URLDecoder;

public class OssUrlUtil {

    private static final Logger logger = LoggerFactory.getLogger(OssUrlUtil.class);

    /**
     * 从OSS URL中提取对象key
     *
     * @param ossUrl OSS完整URL或对象key
     * @return 对象key
     */
    public static String extractObjectKey(String ossUrl) {
        try {
            if (ossUrl == null || ossUrl.trim().isEmpty()) {
                throw new IllegalArgumentException("OSS URL不能为空");
            }

            // 如果不是完整URL，直接返回（可能已经是对象key）
            if (!ossUrl.startsWith("http://") && !ossUrl.startsWith("https://")) {
                return ossUrl;
            }

            // 解析URL
            URL url = new URL(ossUrl);
            String path = url.getPath();

            // 移除开头的斜杠
            if (path.startsWith("/")) {
                path = path.substring(1);
            }

            // URL解码，处理中文文件名
            String decodedPath = URLDecoder.decode(path, "UTF-8");

            logger.debug("原始URL: {}, 提取的key: {}", ossUrl, decodedPath);

            return decodedPath;

        } catch (Exception e) {
            logger.error("提取对象key失败: {}", ossUrl, e);
            throw new RuntimeException("提取对象key失败: " + e.getMessage(), e);
        }
    }

    /**
     * 检查是否为OSS URL
     */
    public static boolean isOssUrl(String url) {
        return url != null && (url.startsWith("http://") || url.startsWith("https://"));
    }

    /**
     * 构建OSS URL
     */
    public static String buildOssUrl(String endpoint, String bucketName, String objectKey) {
        try {
            // 确保endpoint格式正确
            if (!endpoint.startsWith("http://") && !endpoint.startsWith("https://")) {
                endpoint = "https://" + endpoint;
            }

            // 移除endpoint末尾的斜杠
            if (endpoint.endsWith("/")) {
                endpoint = endpoint.substring(0, endpoint.length() - 1);
            }

            // URL编码对象key
            String encodedKey = java.net.URLEncoder.encode(objectKey, "UTF-8")
                    .replace("+", "%20"); // 空格处理

            return String.format("%s/%s/%s", endpoint.replace("://", "://" + bucketName + "."), "", encodedKey);

        } catch (Exception e) {
            logger.error("构建OSS URL失败: endpoint={}, bucket={}, key={}", endpoint, bucketName, objectKey, e);
            throw new RuntimeException("构建OSS URL失败: " + e.getMessage(), e);
        }
    }
}
